<?php

namespace App\Http\Controllers\Api;

use App\Models\Response;
use App\Models\User;
use App\Http\Requests\UserRequest;
use App\Libraries\test\BaseData;
use App\Libraries\test\TestData;
use App\Http\Requests\UserUpdateRequest;
use Illuminate\Support\Facades\App;

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api',["except"=>["store"]]);
    }


    public function store(UserRequest $request) {
        $verifyData = \Cache::get($request->verification_key);
        $code = $request->code;
        $phone = $request->phone;
        if(!$verifyData ) {
            return $this->response->error('验证码已经失效',422);
        }
        $cacheCode = $verifyData['code'];
        if(!hash_equals($code,$cacheCode)) {

            return $this->response->error('验证码错误',422);
        }
        $user = User::create([
            'name' =>$request->name,
            'email'=> $request->email,
            'phone' => $request->phone,
            'password' => bcrypt($request->password)
        ]);

        \Cache::forget($request->verification_key);
        return $this->response->created();
    }

    public function show() {
        $response = new Response();
        $user = auth('api')->user();
        $response->setCode(200);
        $response->setData([
            "user"=>$user
        ]);
        return json_encode($response);
    }

    public function update(UserUpdateRequest $request) {

        $user = auth('api')->user();
        $credential['name'] = $request->name;
        $credential['address'] = $request->address;
        $avatar = $request->avatar;
        //$user->update($credential);
        $client = App::make('aliyun-oss');
        $client->putObject('loadme', "avatar", $avatar);
        $result = $client->getObject("loadme", "avatar");
        echo $result;
    }

    public function test() {

        $data = new BaseData();
        $obj = new TestData();
        $obj->setPhone("18512556616");
        $obj->setUsername("sunleilei");
        $data->setData($obj);
        return json_encode($data);
    }
}
